package tech.aistar.corejava.day13;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: lya
 * @Description: 本类的作用描述:对象的序列化和反序列化
 * @CreateDate: 2019/8/2
 * @Version: 1.0
 */
public class ObjectDemo {
    public static final String PATH = "src/tech/aistar/corejava/day13/products.txt";
    public static void main(String[] args) {
        List<Product> list = new ArrayList<>();
        Product p1 = new Product("宝洁","洗手粉",18.5);
        Product p2 = new Product("联合利华","肥皂",4.5);
        Product p3 = new Product("宝洁","牙膏",32.5);
        Product p4 = new Product("宝洁","毛巾",14.5);
        Product p5 = new Product("洁利","洗面奶",26.0);
        Product p6 = new Product("好迪","洗发水",27.5);
        Product p7 = new Product("多芬","沐浴露",38.5);
        Product p8 = new Product("宝洁","洗洁精",3.4);


        //list.add(p1);
        //list.add(p2);
        list.add(p3);

        //如果分批次进行第二次写入,将不能够读取出来
        //永远仅仅支持一个周期内的一次性写入,一次性读取

        //解决的事情 - 多次分批写入依然能够全部读取出来

//        list.add(p4);
//        list.add(p5);
//        list.add(p6);
//        list.add(p7);
//        list.add(p8);

        //观察  - 文件是否被覆盖还是追加写入

        //writeProduct(list);

        List<Product> pList = readAll();
        if(null != pList){
            pList.forEach(System.out::println);
        }

    }

    /**
     * 对象的反序列化
     * @return
     */
    private static List<Product> readAll() {
        ObjectInputStream in = null;
        List<Product> products = null;
        try {
            in = new ObjectInputStream(new FileInputStream(PATH));

            //读取对象
            products = (List<Product>) in.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally{
            if(null != in){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return products;
    }

    /**
     * 对象的序列化
     * 字节的操作
     * @param products
     */
    private static void writeProduct(List<Product> products) {
        //构建一个支持对象类型的文件的字节输出流
        ObjectOutputStream out = null;

        try {
            //默认会覆盖
            //虽然有追加的方式 - 但是不推荐使用

            out = new ObjectOutputStream(new FileOutputStream(PATH));
            //追加文件写入
            //out = new ObjectOutputStream(new FileOutputStream(PATH,true));

            //写入
            out.writeObject(products);
            System.out.println("写入集合对象成功了!");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != out ){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
